package com.mju.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mju.controller.ex.*;
import com.mju.dao.ReceiveDao;
import com.mju.pojo.Receive;
import com.mju.utils.GetTheCurrentTimeUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

import static com.mju.controller.common.BaseController.AVATAR_MAX_SIZE;
import static com.mju.controller.common.BaseController.AVATAR_TYPE;

/**
* @author LX
* @description 针对表【t_receive】的数据库操作Service实现
* @createDate 2023-10-24 10:47:54
*/
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ReceiveServiceImpl implements IReceiveService {
    @Autowired
    private ReceiveDao receiveDao;
    @SneakyThrows
    @Override
    public Boolean addReceiveInfo(Receive receive) {
        log.info("新建用户回收单...");
        Date currentTime = GetTheCurrentTimeUtils.getTheCurrentTime();
//        Integer rid = Integer.valueOf(VipNoUtils.getNo().substring(7, 13));
//        receive.setRId(rid);
        receive.setReceiveTime(currentTime);
        receive.setStatus(0);
        int result = receiveDao.insert(receive);
        return result>0;
    }

    @Override
    public Boolean reviewReceiveInfo(Integer rid, BigDecimal finalPrice){
        log.info("审核用户回收单...");
        Receive receive = receiveDao.selectById(rid);
        receive.setFinalPrice(finalPrice);
        // 0:待审核 1：已审核 2:用户确认3：等待上门 4：已完成 5：已取消
        receive.setStatus(1);
        int result = receiveDao.updateById(receive);
        return  result>0;
    }

    @Override
    public Boolean faceToFaceReceive(Integer rid, Date predictTimeStart, Date predictTimeEnd) {
        log.info("预约上门时间...");
        Receive receive = receiveDao.selectById(rid);
        receive.setPredictTimeStart(predictTimeStart);
        receive.setPredictTimeEnd(predictTimeEnd);
        // 0:待审核 1：已审核 2:用户确认3：等待上门 4：已完成 5：已取消
        receive.setStatus(3);
        int result = receiveDao.updateById(receive);
        return result>0;
    }

    @SneakyThrows
    @Override
    public Boolean completeReceive(Integer rid){
        log.info("回收单完成...");
        Receive receive = receiveDao.selectById(rid);
        Date currentTime = GetTheCurrentTimeUtils.getTheCurrentTime();
        receive.setFinishTime(currentTime);
        receive.setStatus(4);
        int result = receiveDao.updateById(receive);
        return result>0;
    }

    @Override
    public Boolean waitingForPayment(Integer rid) {
        log.info("已取货，待打款...");
        Receive receive = receiveDao.selectById(rid);
        receive.setStatus(6);
        int result = receiveDao.updateById(receive);
        return result > 0;
    }

    @Override
    public Integer getStatusByRid(Integer rid) {
        log.info("获取回收单状态...");
        Receive receive = receiveDao.selectById(rid);
        return receive.getStatus();
    }


    @SneakyThrows
    @Override
    public Boolean cancelReceive(Integer rid){
        log.info("用户取消回收单...");
        Receive receive = receiveDao.selectById(rid);
        Date currentTime = GetTheCurrentTimeUtils.getTheCurrentTime();
        receive.setFinishTime(currentTime);
        receive.setStatus(5);
        int result = receiveDao.updateById(receive);
        return result>0;
    }

    @Override
    public Boolean userConfirmsReceive(Integer rid){
        log.info("用户确认回收...");
        Receive receive = receiveDao.selectById(rid);
        receive.setStatus(2);
        int result = receiveDao.updateById(receive);
        return result>0;
    }

    @Override
    public Receive updateReceiveInfo(Receive receive){
        log.info("修改回收单信息...");
        receiveDao.updateById(receive);
        Receive newRecevice = receiveDao.selectById(receive);
        return newRecevice;
    }

    @Override
    public Boolean updateStatusByRid(Integer rid, Integer status) {
        log.info("变动回收单状态中...");
        Receive receive = receiveDao.selectById(rid);
        receive.setStatus(status);
        int result = receiveDao.updateById(receive);
        return result>0;
    }

    @Override
    public Boolean updateRepoManByRid(Integer rid, String repoMan) {
        log.info("变动回收人员中...");
        Receive receive = receiveDao.selectById(rid);
        receive.setRepoMan(repoMan);
        int result = receiveDao.updateById(receive);
        return result>0;
    }

    @Override
    public Boolean deleteReceiveInfo(Integer rid){
        log.info("删除回收单...");
        int result = receiveDao.deleteById(rid);
        return result>0;
    }

    @Override
    public String uploadPictures(HttpSession session, MultipartFile file) {
        log.info("上传图片中...");
        if (file.isEmpty()) {// 判断文件是否为空
            throw new FileEmptyException("文件为空");
        }
        if (file.getSize() > AVATAR_MAX_SIZE) {
            throw new FileSizeException(("文件超出限制"));
        }
        // 判断文件的类型是否是我们规定的后缀类型
        String contentType = file.getContentType();
        // AVATAR_TYPE是集合
        if (!AVATAR_TYPE.contains(contentType)) {
            throw new FileTypeException("文件类型不支持");
        }

        // 上传的文件路径: .../upload/文件名.jpg
        // 注意：getServletContext()：获取当前应用程序的上下文，每次启动tomcat都会创建新的上下文
        String parent = session.getServletContext().getRealPath("/upload");
        // 用下面的路径(拦截器要进行相应的映射配置哦)
        //String parent = "/tmp-images"; // 会自动映射到static下的upload文件夹下
        // 判断路径是否存在
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 获取文件名称+后缀
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index); // 获取后缀
        String filename = UUID.randomUUID().toString().toUpperCase() + suffix; // 具体的文件名+后缀
        System.out.println("文件名：" + filename);
        // 在dir所指的对象下，创建文件
        File dest = new File(dir, filename);
        System.out.println("dir:" + dir);
        System.out.println("dest:" + dest);
        try {
            file.transferTo(dest); // 上传头像
        } catch (FileStatusException e) {
            throw new FileStatusException("文件状态异常");
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        }

        //String avatar = "/tmp-images/" + filename;
        String path = "/upload/" + filename;
        return path;
    }

    @Override
    public IPage<Receive> queryAllReceiveInfo(Integer currentPage, Integer pageSize) {
        IPage page = new Page<>(currentPage, pageSize);
        receiveDao.selectPage(page,null);
        return page;
    }

    @Override
    public IPage<Receive> conQueryAllReceiveInfo(Integer currentPage, Integer pageSize, Receive receive) {
        IPage page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Receive> lwq=new LambdaQueryWrapper<>();
        lwq.eq(!Objects.isNull(receive.getRId()), Receive::getRId, receive.getRId());
        lwq.eq(!Objects.isNull(receive.getUId()), Receive::getUId, receive.getUId());
        lwq.like(!Objects.isNull(receive.getUserName()),Receive::getUserName,receive.getUserName());
        lwq.like(!Objects.isNull(receive.getTitle()),Receive::getTitle,receive.getTitle());  // 新增
        lwq.eq(!Objects.isNull(receive.getStatus()),Receive::getStatus,receive.getStatus());
        receiveDao.selectPage(page,lwq);
        return page;
    }
}




